package com.example.caoben_back.config;

import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.service.IUserService;
import com.example.caoben_back.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    
    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return true;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = (String) principals.getPrimaryPrincipal();
        User user = JWTUtil.getPayload(token, User.class);
        
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        
        // 添加角色和权限
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        
        // 示例：根据用户ID或其他条件设置角色和权限
        // 这里可以根据实际业务需求进行修改
        if (user != null) {
            roles.add("user");
            permissions.add("user:view");
            
            // 管理员特殊处理
            if (user.getIfAmdin() != null && user.getIfAmdin() == 1) { // 使用新添加的字段判断是否为管理员
                roles.add("admin");
                permissions.add("admin:view");
                permissions.add("admin:edit");
            }
        }
        
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        if (token.isEmpty()) {
            throw new AuthenticationException("token为空!");
        }
        
        // 验证token有效性
        if (!JWTUtil.verify(token, jwtUtil.getSecret())) {
            throw new AuthenticationException("token验证失败!");
        }
        
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}